package com.ling.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ling.bean.*;
import com.ling.dto.RecommendationDto;
import com.ling.service.*;
import com.ling.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class UserQuestionController {
    private final QuestionService questionService;
    private final QuestionUserListService questionUserListService;
    private final StarQuestionService starQuestionService;
    private final UserService userService;
    private final UserAreaService userAreaService;

    @Autowired
    public UserQuestionController(QuestionService questionService, QuestionUserListService questionUserListService, StarQuestionService starQuestionService, UserService userService, UserAreaService userAreaService) {
        this.questionService = questionService;
        this.questionUserListService = questionUserListService;
        this.starQuestionService = starQuestionService;
        this.userService = userService;
        this.userAreaService = userAreaService;
    }

    @RequestMapping(value = "/question-all", method = RequestMethod.GET)
    public String goToUserAllQuestion() {
        return "/question-all";
    }

    //查询指定用户发布的提问
    @RequestMapping(value = "/userQuestion/{userId}/{pn}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getUserQuestion(@PathVariable String userId, @PathVariable Integer pn, HttpSession session) {
        //判断登录用户是否与uri中的userId一致
        User user = (User) session.getAttribute("user");
        if (user == null || !userId.equals(user.getId())) {
            return Msg.fail().add("error", "用户未登录或登录出错，请重新登录！");
        }
        //开始分页
        PageHelper.startPage(pn, 10);
        List<Question> userQuestion = questionService.getUserQuestion(userId);
        PageInfo<Question> pageInfo = new PageInfo<>(userQuestion);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //跳转到提问页面
    @RequestMapping(value = "/question-write", method = RequestMethod.GET)
    public String goToUserQuestionWrite() {
        return "question-write";
    }

    //用户提问
    @RequestMapping(value = "/postQuestion", method = RequestMethod.POST)
    @ResponseBody
    public Msg postQuestion(Question question, HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请重新登录");
        }
        String questionId = StringUtil.getRandomString(16);
        question.setId(questionId);
        question.setEdittime(new Date());
        questionService.saveQuestion(question);

        //插入到elasticsearch数据库中
        String url = "http://localhost:9200/question/question/" + question.getId();
        System.out.println("正在存放问题"+question.getId());
        RecommendationDto recommendationDto = new RecommendationDto();
        recommendationDto.setId(question.getId());
        recommendationDto.setType(0);
        recommendationDto.setTitle(question.getQuestiontitle());
        recommendationDto.setContent(question.getQuestioncontent().replaceAll("<[.[^<]]*>", ""));
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.put(url,recommendationDto);

        //经验值+5
        User userById = userService.getUserById(user.getId());
        userById.setJiyan(userById.getJiyan() + 5);
        userService.updateUserProfile(userById);
        httpSession.setAttribute("user", userById);
        //能力+5
        UserArea userArea = userAreaService.getUserArea(user.getId(), question.getAreaid());
        if (userArea != null) {
            userArea.setAbility(userArea.getAbility() + 5);
            userAreaService.updateAbility(userArea);
        } else {
            UserArea userArea1 = new UserArea();
            userArea1.setId(StringUtil.getRandomString(16));
            userArea1.setAbility(0);
            userArea1.setAreaid(question.getAreaid());
            userArea1.setUserid(user.getId());
            userAreaService.saveUserArea(userArea1);
        }
        String areaid = question.getAreaid();
        //获取当前领域排名较前的用户
        List<String> userOrderByAreaId = userService.getUserOrderByAreaId(areaid);
        QuestionUserList questionUserList;
        for (String userId : userOrderByAreaId) {
            //循环给每一个用户发送邀请回答
            questionUserList = new QuestionUserList();
            questionUserList.setHasread(false);
            questionUserList.setId(StringUtil.getRandomString(16));
            questionUserList.setQuestionid(questionId);
            questionUserList.setUserid(userId);
            questionUserListService.addQuestionUserList(questionUserList);
        }
        return Msg.success().add("questionId", questionId);
    }

    //删除问题
    @RequestMapping(value = "/deleteUserQuestion/{questionId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg deleteUserQuestion(@PathVariable String questionId, HttpSession session) {
        Question userQuestionById = questionService.getUserQuestionById(questionId);
        if (userQuestionById != null) {
            User user = (User) session.getAttribute("user");
            if (user != null) {
                if (user.getId().equals(userQuestionById.getUserid())) {
                    questionService.deleteQuestionById(questionId);
                    return Msg.success();
                } else {
                    return Msg.fail().add("error", "你无权删除该问题！");
                }
            } else {
                return Msg.fail().add("error", "请登录后重试！！！");
            }
        } else {
            return Msg.fail().add("error", "该问题不存在！！！");
        }
    }

    //管理员删除问题
    @PostMapping("/delQuestion/{questionId}")
    @ResponseBody
    public Msg delQuestion(@PathVariable String questionId) {
        questionService.deleteQuestionById(questionId);
        return Msg.success();
    }

    //跳转到修改问题
    @RequestMapping(value = "/question-update/{questionId}")
    public String goToUpdateQuestion(ModelMap map, @PathVariable String questionId, HttpSession session) {

        Question userQuestionById = questionService.getUserQuestionById(questionId);
        if (userQuestionById != null) {
            //该问题不为空，判断用户是否有权限
            User user = (User) session.getAttribute("user");
            if (user != null) {
                //用户已登录
                if (user.getId().equals(userQuestionById.getUserid())) {
                    //有权限
                    map.addAttribute("question", userQuestionById);
                    return "question-update";
                } else {
                    return "redirect:/error";
                }
            } else {
                //跳转到登录页面
                return "login";
            }
        } else {
            //该问题为空，返回到404页面
            return "redirect:/error";
        }
    }

    //提交修改问题
    @RequestMapping(value = "/questionUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Msg updateUserQuestion(Question question) {
        questionService.updateQuestion(question);
        return Msg.success().add("questionId", question.getId());
    }

    //邀请用户回答
    @RequestMapping(value = "/inviteUser/{questionId}/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg inviteUserToAnswer(@PathVariable String questionId, @PathVariable String userId) {
        QuestionUserList questionUserList = new QuestionUserList();
        questionUserList.setHasread(false);
        questionUserList.setId(StringUtil.getRandomString(16));
        questionUserList.setQuestionid(questionId);
        questionUserList.setUserid(userId);
        //插入数据
        questionUserListService.addQuestionUserList(questionUserList);
        return Msg.success();
    }

    //跳转到查看用户关注问题页面
    @RequestMapping(value = "/question-star", method = RequestMethod.GET)
    public String goToUserQuestionStar(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        //用户已经登录
        return "/question-star";
    }

    //获取到指定用户关注的问题
    @RequestMapping(value = "/starQuestion/{userId}/{pn}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getUserStarQuestionList(@PathVariable String userId, @PathVariable Integer pn) {
        PageHelper.startPage(pn, 10);
        List<Question> questionList = starQuestionService.getStarQuestion(userId);
        PageInfo<Question> pageInfo = new PageInfo<>(questionList);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //取消关注问题
    @RequestMapping(value = "/cancelStarQuestion/{userId}/{questionId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg cancelStarQuestion(@PathVariable String userId, @PathVariable String questionId) {
        starQuestionService.delStarQuestionById(userId, questionId);
        return Msg.success();
    }

    //用户点击关注问题按钮
    @RequestMapping(value = "/addStarQuestion/{userId}/{questionId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg starQuestion(@PathVariable String userId, @PathVariable String questionId, HttpSession session) {
        //判断用户是否登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请登录后重试！");
        }

        //判断是否已关注
        if (starQuestionService.hasStarred(userId, questionId)) {
            return Msg.fail().add("error", "已关注过该问题，请不要重复操作！");
        } else {
            //添加关注记录
            StarQuestion starQuestion = new StarQuestion();
            starQuestion.setId(StringUtil.getRandomString(16));
            starQuestion.setQuestionid(questionId);
            starQuestion.setUserid(userId);
            starQuestionService.addStarQuestion(starQuestion);
        }
        return Msg.success();
    }
}
